/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is ThumbsDown.
 *
 * The Initial Developer of the Original Code is
 * Atte Kemppilä.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 * ***** END LICENSE BLOCK ***** */


function RegExpPage() // extend WizardPage
{
    var depends = "images script";
    WizardPage.call(this, depends);
}

RegExpPage.prototype =
{
    onPageShow: function()
    {
        let self = this;
        
        if (this.firstRun)
        {
            this.$deck = document.getElementById("deck_regexp");
            this.$source = document.getElementById("rgroup_source");
            this.pattern = {get $selected() { return this["$" + self.$source.value]; }};
            this.pattern.$thumbnail = document.getElementById("tbox_pattern_thumbnail");
            this.pattern.$link = document.getElementById("tbox_pattern_link");
            this.pattern.$resetDefault = document.getElementById("btn_pattern_resetDefault");
            this.pattern.$resetScript = document.getElementById("btn_pattern_resetScript");
            this.template = {get $selected() { return this["$" + self.$source.value]; }};
            this.template.$thumbnail = document.getElementById("tbox_template_thumbnail");
            this.template.$link = document.getElementById("tbox_template_link");
            this.template.$resetDefault = document.getElementById("btn_template_resetDefault");
            this.template.$resetScript = document.getElementById("btn_template_resetScript");
            this.$thumbnailList = document.getElementById("rlbox_regexp_thumbnail");
            this.$thumbnailImageList = document.getElementById("rlbox_regexp_thumbnail_images");
            this.$linkList = document.getElementById("rlbox_regexp_link");
            this.$linkImageList = document.getElementById("rlbox_regexp_link_images");
        }
        
        // populate listboxes
        if (this.dirty.images)
        {
            this.entries =
                scriptWizard.getEntries({
                    thumbnail: model.selected,
                    linkUrl: model.linkUrls,
                    image: model.images,
                });
            
            clearListbox(this.$thumbnailList);
            clearListbox(this.$thumbnailImageList);
            clearListbox(this.$linkList);
            clearListbox(this.$linkImageList);
            
            for each (let entry in this.entries)
            {
                this.$thumbnailList.appendItem(entry.thumbnailUrl);
                this.$thumbnailImageList.appendItem(entry.image.src, entry.thumbnailUrl);
                this.$linkList.appendItem(entry.linkUrl);
                this.$linkImageList.appendItem(entry.image.src, entry.linkUrl);
            }
        }
        
        // pattern & template
        if (this.dirty.images || this.dirty.script)
        {
            for each (let source in ["thumbnail", "link"])
            {
                let script = model.script;
                if (! (script && (script.type == "regexp") && (script.source == source)))
                    script = null;
                
                let sourceUrls = [entry[source + "Url"] for each (entry in this.entries)];
                let sourceUrlTokens = scriptWizard.getUrlTokens(sourceUrls);
                this.pattern[source] = {};
                this.pattern[source].default = scriptWizard.resolveUrlRegExp(sourceUrlTokens, true);
                this.pattern[source].script = (script ? script.pattern.pattern : "");
                let pattern = (script ? this.pattern[source].script : this.pattern[source].default);
                
                let targetUrls = [entry.image.src for each (entry in this.entries)];
                this.template[source] = {};
                this.template[source].default = scriptWizard.getTemplate(sourceUrls, targetUrls, pattern);
                this.template[source].script = (script ? script.template : "");
                let template = (script ? this.template[source].script : this.template[source].default);
                
                this.pattern["$" + source].value = pattern;
                this.template["$" + source].value = template;
            }
            
            this.pattern.$resetScript.hidden = (! model.script);
            this.template.$resetScript.hidden = (! model.script);
        }
        
        if (this.dirty.page)
        {
            this._updateButtons();
            this._updatePattern();
            this._updateTemplate();
        }
    },
    
    onSourceSelect: function()
    {
        let source = this.$source.value;
        let _source = "$" + source;
        
        document.getElementById("deck_pattern").selectedPanel = this.pattern[_source];
        document.getElementById("deck_template").selectedPanel = this.template[_source];
        document.getElementById("deck_sources").selectedPanel = document.getElementById("box_sources_" + source);
        document.getElementById("lbl_pattern").control = this.pattern[_source];
        document.getElementById("lbl_template").control = this.template[_source];
        
        this._updateButtons();
        this._updatePattern();
        this._updateTemplate();
        wizard.updateWizardButtons();
    },
    
    onPatternInput: function()
    {
        // update buttons immediately so that textbox content and buttons are in sync
        this._updateButtons();
        // canAdvance() depends on textbox's timer
        callLater(0, null, function() { wizard.updateWizardButtons() });
    },
    
    onPatternCommand: function()
    {
        if (page != pages["regexp"])
            return;
        
        this._updateButtons();
        this._updatePattern();
        wizard.updateWizardButtons();
    },
    
    onTemplateInput: function()
    {
        // update buttons immediately so that textbox content and buttons are in sync
        this._updateButtons();
        // canAdvance() depends on textbox's timer
        callLater(0, null, function() { wizard.updateWizardButtons() });
    },
    
    onTemplateCommand: function()
    {
        if (page != pages["regexp"])
            return;
        
        this._updateButtons();
        this._updateTemplate();
        wizard.updateWizardButtons();
    },
    
    resetPattern: function(source)
    {
        this.pattern.$selected.value = this.pattern[this.$source.value][source];
        
        this._updateButtons();
        this._updatePattern();
        wizard.updateWizardButtons();
    },
    
    resetTemplate: function(source)
    {
        this.template.$selected.value = this.template[this.$source.value][source];
        
        this._updateButtons();
        this._updateTemplate();
        wizard.updateWizardButtons();
    },
    
    onImageListDoubleClick: function(e)
    {
        if (e.button != 0)
            return;
        
        let rlitem = e.target;
        while (rlitem && (rlitem.nodeName != "richlistitem"))
            rlitem = rlitem.parentNode;
        
        if (! rlitem)
            return;
        
        let sourceUrl = rlitem.value;
        let imageUrl = rlitem.label;
        
        let title = _("editImageUrl.title");
        let message = _("editImageUrl.message");
        let value = {value: imageUrl};
        let result = Services.prompt.prompt(window, title, message, value, null, {});
        if (! result)
            return;
        
        imageUrl = value.value;
        let rlbox = rlitem.parentNode;
        let index = rlbox.getIndexOfItem(rlitem);
        rlbox.removeItemAt(index);
        rlbox.insertItemAt(index, imageUrl, sourceUrl);
        
        this._updateTemplate();
        wizard.updateWizardButtons();
    },
    
    _updateButtons: function()
    {
        let source = this.$source.value;
        this.pattern.$resetDefault.disabled = (this.pattern.$selected.value == this.pattern[source].default);
        this.pattern.$resetScript.disabled = (this.pattern.$selected.value == this.pattern[source].script);
        this.template.$resetDefault.disabled = (this.template.$selected.value == this.template[source].default);
        this.template.$resetScript.disabled = (this.template.$selected.value == this.template[source].script);
    },
    
    _updatePattern: function()
    {
        var pattern = "^" + this.pattern.$selected.value + "$";
        document.getElementById("rlbox_regexp_" + this.$source.value).pattern = pattern;
        document.getElementById("rlbox_regexp_" + this.$source.value + "_images").pattern = pattern;
    },
    
    _updateTemplate: function()
    {
        var template = this.template.$selected.value;
        document.getElementById("rlbox_regexp_" + this.$source.value + "_images").template = template;
    },
    
    canAdvance: function()
    {
        if (this.isHelpOpen)
            return false;
        
        // textbox input is pending
        if (this.pattern.$selected._timer || this.template.$selected._timer)
            return false;
        
        if (! document.getElementById("rlbox_regexp_" + this.$source.value).match)
            return false;
        
        if (! document.getElementById("rlbox_regexp_" + this.$source.value + "_images").match)
            return false;
        
        return true;
    },
    
    onPageAdvanced: function()
    {
        model.type = "regexp";
        model.source = this.$source.value;
        model.pattern = this.pattern.$selected.value;
        model.template = this.template.$selected.value;
        return wizard.advance("script");
    }
}

extend(RegExpPage, WizardPage);

pages["regexp"] = new RegExpPage();
